package com.hzdesk.media.koreabatchmatvector.logic.persenter;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.MediaCodecInfo;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.hzdesk.media.koreabatchmatvector.R;
import com.hzdesk.media.koreabatchmatvector.base.MyClientApplication;
import com.hzdesk.media.koreabatchmatvector.bean.MouseUserDevicesinfoBean;
import com.hzdesk.media.koreabatchmatvector.config.AppConfig;
import com.hzdesk.media.koreabatchmatvector.config.RxBusUtil;
import com.hzdesk.media.koreabatchmatvector.custom.SketchpadView;
import com.hzdesk.media.koreabatchmatvector.dao.MouseUserDevicesinfoDaoUtils;
import com.hzdesk.media.koreabatchmatvector.dialog.ColorPopWindow;
import com.hzdesk.media.koreabatchmatvector.dialog.LoadingDialog;
import com.hzdesk.media.koreabatchmatvector.dialog.RightViewPopWindow;
import com.hzdesk.media.koreabatchmatvector.dialog.StrokesPopWindow;
import com.hzdesk.media.koreabatchmatvector.inter.ColorChangeClick;
import com.hzdesk.media.koreabatchmatvector.inter.RightViewClick;
import com.hzdesk.media.koreabatchmatvector.inter.StrokesChangeClick;
import com.hzdesk.media.koreabatchmatvector.logic.contract.RecordScreenLabeledContract;
import com.hzdesk.media.koreabatchmatvector.matvector.HDMIRxPlayer;
import com.hzdesk.media.koreabatchmatvector.screenrecord.AudioEncodeConfig;
import com.hzdesk.media.koreabatchmatvector.screenrecord.ScreenRecorder;
import com.hzdesk.media.koreabatchmatvector.screenrecord.VideoEncodeConfig;
import com.hzdesk.media.koreabatchmatvector.service.RecordService;
import com.hzdesk.media.koreabatchmatvector.service.ScreenRecordService;
import com.hzdesk.media.koreabatchmatvector.utils.MyToastUtils;
import com.hzdesk.media.koreabatchmatvector.utils.RxBus;
import com.hzdesk.media.koreabatchmatvector.utils.SharedPreferencesUtils;
import com.hzdesk.media.koreabatchmatvector.utils.UsbDeviceUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static com.hzdesk.media.koreabatchmatvector.screenrecord.ScreenRecorder.VIDEO_AVC;

/**
 * Created by Administrator on 2018/6/23.
 * 杭州席媒科技有限公司  Developers  刘传华  09
 * 佛祖镇楼 bug辟易
 */

public class RecordScreenLabeledPersenter implements RecordScreenLabeledContract.IRecordScreenLabeledPersenter {

    private String TAG = "RecordScreenLabeledPersenter";
    private RecordScreenLabeledContract.IRecordScreenLabeledView iRecordScreenLabeledView;
    private RecordService.RecordBind recordBind;
    private RecordService recordService;

    private boolean recording = false;
    private boolean isRecordScreen = false;
    private boolean isMenuShow=false;
    public ViewGroup m_Root;
    public HDMIRxPlayer m_HDMIRxPlayer = null;
    private boolean isShow = true;
    private SketchpadView mSketchpadView;
    private Activity context;
    private ColorPopWindow colorPopWindow;
    private StrokesPopWindow strokesPopWindow;
    RightViewPopWindow rightViewPopWindow;
    private LoadingDialog loadingDialog;
    private long time = 0;

    private ScreenRecordService screenRecordService;
    private ScreenRecordService.RecordBinder recordBinder;
    private MediaProjectionManager mMediaProjectionManager;
    private static final int REQUEST_MEDIA_PROJECTION = 1;
    private static final int REQUEST_PERMISSIONS = 2;
    private int resultCode;
    private Intent data;


    public RecordScreenLabeledPersenter(RecordScreenLabeledContract.IRecordScreenLabeledView mRecordScreenLabeledView) {
        this.iRecordScreenLabeledView = mRecordScreenLabeledView;
    }

    @Override
    public void initView(Activity mContext, SketchpadView sketchpadView) {
        context = mContext;
        mMediaProjectionManager = (MediaProjectionManager) mContext.getApplicationContext().getSystemService(mContext.MEDIA_PROJECTION_SERVICE);
        colorPopWindow = new ColorPopWindow(mContext); //  颜色弹框
        strokesPopWindow = new StrokesPopWindow(mContext);//  笔触弹框
        rightViewPopWindow = new RightViewPopWindow(mContext); // 鼠标右键弹框
        loadingDialog = new LoadingDialog(mContext); //  加载中进度提示框
        mSketchpadView = sketchpadView;
        mSketchpadView.setContext(mContext);
        initLoadingListen();
        initMouseListen(sketchpadView);
        initColorlisten();
        initStrokesListen();
    }

    // 笔触弹窗 ==================================================
    private void initStrokesListen() {
        strokesPopWindow.setStrokesChangeClickListener(new StrokesChangeClick() {
            @Override
            public void click(int num) {
                switch (num) {
                    case 1: //size 1
                        changeSize(3);
                        break;
                    case 2:  //size 2
                        changeSize(5);
                        break;
                    case 3: //size 3
                        changeSize(7);
                        break;
                    case 4: //size 4
                        changeSize(9);
                        break;
                }
            }
        });

    }

    private void changeSize(int size) {
        mSketchpadView.setStrokeSize(size, mSketchpadView.STROKE_PEN);
        //MyClientApplication.getUserBeanList(context).get(MyClientApplication.getUserNum() -1).setBrushSize(size);
        MouseUserDevicesinfoBean bean = MyClientApplication.getMouseUserDeviceinfoBean(context, MyClientApplication.getUserNum());
        bean.setBrushSize(size);
        MyClientApplication.changeMouseUserDevicesinfoBean(context, bean);
        iRecordScreenLabeledView.showUser(MyClientApplication.getMouseUserDeviceinfoBean(context, MyClientApplication.getUserNum()));
    }

    // 颜色弹窗 ============================================
    private void initColorlisten() {
        colorPopWindow.setColorChangeClickListener(new ColorChangeClick() {
            @Override
            public void click(String color) {
                changeColor(color);
            }
        });
    }


    private void changeColor(String color) {
        mSketchpadView.setStrokeColor(color);
        //MyClientApplication.getUserBeanList().get(MyClientApplication.getUserNum()-1).setColorindex(index);
        //MyClientApplication.getUserBeanList(context).get(MyClientApplication.getUserNum() -1).setColor(color);

        MouseUserDevicesinfoBean bean = MyClientApplication.getMouseUserDeviceinfoBean(context, MyClientApplication.getUserNum());
        bean.setColor(color);
        MyClientApplication.changeMouseUserDevicesinfoBean(context, bean);
        iRecordScreenLabeledView.showUser(MyClientApplication.getMouseUserDeviceinfoBean(context, MyClientApplication.getUserNum()));


    }

    // 进度初始化=============================================
    private void initLoadingListen() {
        RxBus.getInstance().subscribe(String.class, new io.reactivex.functions.Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                if (o.equals(RxBusUtil.SHOW_LOAD_DIALOG)) { // todo 显示加载 ShowLoadDialog
                    showLoadDialog();// todo 显示加载中进度提示框
                }
                if (o.equals(RxBusUtil.DISMISS_LOAD_DIALOG)) { // todo 隐藏加载 DismissLoadDialog
                    dismissLoadDialog();// todo 隐藏加载中进度提示框
                }
            }
        });
    }

    private void dismissLoadDialog() {
        loadingDialog.dismiss();
    }

    private void showLoadDialog() {
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setCancelable(false);
        loadingDialog.show();
    }

    // 鼠标初始化 =============================================
    private void initMouseListen(SketchpadView sketchpadView) {
        sketchpadView.setOnHoverListener(new View.OnHoverListener() {
            @Override
            public boolean onHover(View v, MotionEvent event) {
                int what = event.getAction();
                switch (what) {
                    case MotionEvent.ACTION_HOVER_ENTER:
                        Log.d(TAG, "ENTER");
                        // 鼠标进入view
                        getUser(event);
                        break;
                    case MotionEvent.ACTION_HOVER_EXIT:
                        break;
                    case MotionEvent.ACTION_HOVER_MOVE:
                        break;
                }
                return false;
            }
        });
        sketchpadView.setOnGenericMotionListener(onGenericMotionListener);
    }

    // todo 获取用户
    @SuppressLint("StaticFieldLeak")
    private void getUser(MotionEvent event) {
        new AsyncTask<MotionEvent, Void, Integer>() {
            @Override
            protected Integer doInBackground(MotionEvent... params) {
                return UsbDeviceUtil.getUsbNumber(params[0]);
            }

            protected void onPostExecute(Integer result) {
                if (result > 0) {
                    MyClientApplication.setIsCanDraw(true);
                    if (result != MyClientApplication.getUserNum()) {
                        Log.d(TAG, "getuser:" + result);
                        MyClientApplication.setUserNum(result);
                        //iRecordScreenLabeledView.showUser(MyClientApplication.getUserBeanList(context).get(result-1));
                        iRecordScreenLabeledView.showUser(MyClientApplication.getMouseUserDeviceinfoBean(context, MyClientApplication.getUserNum()));
                        changeUser(result);
                    }

                } else {
                    if (MyClientApplication.isCanDraw()) {
                        MyClientApplication.setIsCanDraw(false);
                        MyToastUtils.ShortToaseShow(context, context.getResources().getString(R.string.unidentified_mouse));
                    }

                }

            }

        }.execute(event);
    }

    // todo 右键菜单
    private View.OnGenericMotionListener onGenericMotionListener = new View.OnGenericMotionListener() {
        @Override
        public boolean onGenericMotion(View view, MotionEvent motionEvent) {
            switch (motionEvent.getButtonState()) {
                case MotionEvent.ACTION_DOWN:  // 悬浮
                    break;
                case MotionEvent.BUTTON_PRIMARY: //左键单击
                    break;
                case MotionEvent.BUTTON_TERTIARY: //中键单击
                    break;
                case MotionEvent.EDGE_RIGHT: //右键单击
                    rightViewPopWindow.dissmissWindow();
                    rightViewPopWindow.showPopupWindow((int) motionEvent.getX(), (int) motionEvent.getY());
                    //todo 监听鼠标右键弹框
                    rightViewPopWindow.setOnRightViewClickListener(new RightViewClick() {
                        @Override
                        public void clickback(int num) {
                            switch (num) {
                                case 1: //todo  返回
                                    iRecordScreenLabeledView.tofinshPager();
                                    break;
                                case 2: //todo  取消
                                    break;
                                case 3: //todo   清除
                                    clearAllStrokes(2);
                                    break;
                                //undo
                                case 4: //todo    撤销
                                    undo();
                                    break;
                                //redo
                                case 5: //todo     重绘
                                    redo();
                                    break;
                            }
                        }
                    });
                    break;
            }
            return true;
        }
    };


    // todo 录屏==============================================
    @Override
    public void onClickedPlayer(Context mContext) {

        if (SharedPreferencesUtils.getProtocal(mContext) == 1) {
            //HDMI IN 使用hdmi in录制
            if (recording) {  // recording true 录屏  false 不录屏
                if (m_HDMIRxPlayer != null) {
                    recordService.setHDMIRxPlayer(m_HDMIRxPlayer);
                    recordService.startRecord(mContext, true);
                    iRecordScreenLabeledView.showMesssage("开始");
                    recording = false;
                    iRecordScreenLabeledView.onstartRecord();
                } else {
                    recording = true;
                    iRecordScreenLabeledView.showMesssage("失败");
                }
            } else {
                recordService.stopRecord(mContext, false);
                iRecordScreenLabeledView.showMesssage("关闭");
                recording = true;
                iRecordScreenLabeledView.onstopRecrd();
            }
        } else {
            if (isRecordScreen) {
                iRecordScreenLabeledView.onstopRecrd();
                stopScreenRecord();
                iRecordScreenLabeledView.showMesssage("关闭");
            } else {
                iRecordScreenLabeledView.onstartRecord();
                startCaptureIntent();
                iRecordScreenLabeledView.showMesssage("开始");
            }


        }
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            recordBind = (RecordService.RecordBind) service;
            recordService = recordBind.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    private ServiceConnection connection_screenrecord = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            recordBinder = (ScreenRecordService.RecordBinder) iBinder;
            screenRecordService = recordBinder.getService();
            screenRecordService.setRecordCallback(new ScreenRecordService.RecordCallback() {
                @Override
                public void SubSectionRecord() {
                    startCaptureIntent();
                    MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
                    screenRecordService.setmMediaProjection(mediaProjection);
                    screenRecordService.subSectionScreenRecord();

                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    public void bindRecordScreenService(FrameLayout FrameLayout, Context mContext) {
        try {
            // m_Root = (ViewGroup) FrameLayout;
            //m_HDMIRxPlayer = new HDMIRxPlayer(mContext, m_Root, AppConfig.SCREEN_WIDTH, AppConfig.SCREEN_HIGHR);
            if (SharedPreferencesUtils.getProtocal(context) == 1) {
                Intent intent = new Intent(mContext, RecordService.class);
                mContext.startService(intent);
                mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE);
            } else {
                Intent intent1 = new Intent(context, ScreenRecordService.class);
                mContext.bindService(intent1, connection_screenrecord, Context.BIND_AUTO_CREATE);
            }


        } catch (Exception e) {
        }
    }

    @Override
    public void unbindRecordScreenService(Context mContext) {
        try {
            //m_HDMIRxPlayer.stop();
            //m_HDMIRxPlayer.release();

            if (SharedPreferencesUtils.getProtocal(mContext) == 1) {

                recordService.stopRecord(mContext, false);
                Intent stopIntent = new Intent(mContext, RecordService.class);
                mContext.stopService(stopIntent);
                mContext.unbindService(connection);
            } else {
                Intent intent = new Intent(mContext, ScreenRecordService.class);
                mContext.unbindService(connection_screenrecord);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // todo 点击事件 ==============================================
    @Override
    public void setStrokeType(int type) {
        mSketchpadView.setStrokeType(type);
        changeType(type);

    }

    private void changeType(int type) {
        MouseUserDevicesinfoBean bean = new MouseUserDevicesinfoBean();
        MouseUserDevicesinfoDaoUtils mouseUserDevicesinfoDaoUtils = new MouseUserDevicesinfoDaoUtils(context);
        List<MouseUserDevicesinfoBean> list = mouseUserDevicesinfoDaoUtils.queryAll();
        for (MouseUserDevicesinfoBean bean1 : list) {
            if (bean1.getMouseNum() == MyClientApplication.getUserNum()) {
                bean = bean1;
                break;
            }
        }
        bean.setType(type);
        mouseUserDevicesinfoDaoUtils.update(bean);

    }

    @Override
    public void changeStroke(LinearLayout linearLayout) {
        strokesPopWindow.showPopupWindow(linearLayout);

    }

    @Override
    public void changeStrokeColor(LinearLayout linearLayout) {
        colorPopWindow.showPopupWindow(linearLayout);

    }

    @Override
    public void undo() {
        mSketchpadView.undo();

    }

    @Override
    public void redo() {
        mSketchpadView.redo();

    }

    @Override
    public void clearAllStrokes(int type) {
        mSketchpadView.clearAllStrokes(type);

    }

    @Override
    public void setOnMenuShowListener(RelativeLayout view) {
        view.setOnHoverListener(onHoverListener);
    }

    @Override
    public void setOnMenuHideListener(LinearLayout listener) {
        listener.setOnHoverListener(onMenuHoverListener);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            this.resultCode = resultCode;
            this.data = data;
            MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
            Log.d(TAG, "resultCode:" + resultCode + "|" + data.getDataString());
            if (mediaProjection == null) {
                Log.e("@@", "media projection is null");
                return;
            }
            //开始
            isRecordScreen = true;
            screenRecordService.setmMediaProjection(mediaProjection);
            screenRecordService.startScreenRecord();
        }
    }


    /**
     * 开始录制屏幕
     */
    private void startCaptureIntent() {
        Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
        context.startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION);
    }

    /**
     * 停止录制屏幕
     */
    private void stopScreenRecord() {
        isRecordScreen = false;
        screenRecordService.stopRecorder(false);
    }


    // todo 底部栏打开关闭 =======================================================================
    @Override
    public void onclickedBottomColumnShowOrHide(LinearLayout mLinearLayoutOne, LinearLayout mLinearLayoutTwo) {
        if (isShow) {
            hiddMenu(mLinearLayoutOne, mLinearLayoutTwo);
        } else {
            showMenu(mLinearLayoutOne, mLinearLayoutTwo);
        }
    }

    //显示菜单
    private void showMenu(LinearLayout mLinearLayoutOne, LinearLayout mLinearLayoutTwo) {
        float a = mLinearLayoutOne.getWidth();
        float b = mLinearLayoutTwo.getWidth();
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(mLinearLayoutOne, "translationX", b, a);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(mLinearLayoutOne, "translationX", a, 0f);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playSequentially(animator1, animator2);
        animatorSet.setDuration(200);
        animatorSet.start();
        isShow = !isShow;
    }

    //隐藏菜单
    private void hiddMenu(LinearLayout mLinearLayoutOne, LinearLayout mLinearLayoutTwo) {
        float a = mLinearLayoutOne.getWidth();
        float b = mLinearLayoutTwo.getWidth();
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(mLinearLayoutOne, "translationX", 0f, a);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(mLinearLayoutOne, "translationX", a, b);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playSequentially(animator1, animator2);
        animatorSet.setDuration(200);
        animatorSet.start();
        isShow = !isShow;
    }

    private void changeUser(int num) {
        MouseUserDevicesinfoBean bean = MyClientApplication.getMouseUserDeviceinfoBean(context, MyClientApplication.getUserNum());
        colorPopWindow.changeUser();
        if (bean.getDisMouse() != 1) {
            mSketchpadView.setStrokeColor(bean.getColor());
            mSketchpadView.setStrokeSize(bean.getBrushSize(), mSketchpadView.STROKE_PEN);
            mSketchpadView.setStrokeType(bean.getType());
        } else {
            mSketchpadView.setStrokeColor("00000000");
        }

    }

    @Override
    public void onclickedFile() {
        if (!MyClientApplication.isRecording()){
            iRecordScreenLabeledView.toDialogPager();

        }else {
            MyToastUtils.ShortToaseShow(context,"录制中");
        }
    }

    @Override
    public void onclickeSetting() {
        if (!MyClientApplication.isRecording()){
            iRecordScreenLabeledView.toSettingPager();
        }else {
            MyToastUtils.ShortToaseShow(context,"录制中");
        }
    }

    private View.OnHoverListener onHoverListener = new View.OnHoverListener() {
        @Override
        public boolean onHover(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_HOVER_ENTER:
                    iRecordScreenLabeledView.onshowMenu();
                    isMenuShow=true;
                    break;
                case MotionEvent.ACTION_HOVER_EXIT:
                    break;
                case MotionEvent.ACTION_HOVER_MOVE:
                    break;
            }
            return false;
        }
    };

    private View.OnHoverListener onMenuHoverListener = new View.OnHoverListener() {
        @Override
        public boolean onHover(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_HOVER_ENTER:
                    break;
                case MotionEvent.ACTION_HOVER_EXIT:
                    //iRecordScreenLabeledView.onhideMenu();
                    new HideMenuThread().run();

                    break;
                case MotionEvent.ACTION_HOVER_MOVE:
                    break;
            }
            return false;
        }
    };

    private class HideMenuThread implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(500);
                if (isMenuShow){
                    iRecordScreenLabeledView.onhideMenu();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }


}
